Skip to content

add symbols Django exports but the stubs omit - #405

Merged
kodiakhq[bot] merged 7 commits into
sbdchd:mainfrom
NorthIsUp:add-missing-symbols
Sep 17, 2026
Merged

kodiakhq[bot] merged 7 commits into
sbdchd:mainfrom
NorthIsUp:add-missing-symbols

Conversation

@NorthIsUp

@NorthIsUp NorthIsUp commented Sep 15, 2026 •

Copy link
Copy Markdown

These symbols all exist at runtime and are importable from the documented public location, but the stubs don't declare them, so a strict checker rejects the import.

Symbol Where it lives Gap
AsyncClient, AsyncRequestFactory django.test defined in test/client.pyi, never re-exported from test/__init__.pyi
HttpResponseBase django.http defined in http/response.pyi, not re-exported
TestCase.captureOnCommitCallbacks django.test context manager since Django 3.2, absent
storages, StorageHandler, InvalidStorageError django.core.files.storage storage-alias registry added in Django 4.2, absent
parse_header_parameters django.utils.http absent; declared with the Django 6.0 signature, (line, max_length=10000)
AdminSite.get_model_admin django.contrib.admin added in Django 5.0 as the supported alternative to reading the private _registry, absent
HttpResponseBase.__contains__ django.http aliased to has_header at runtime, so "Retry-After" in response is the documented spelling; only has_header was declared

Verified against Django 6.0.8:

>>> from django.core.files.storage import storages, InvalidStorageError   # OK
>>> from django.utils.http import parse_header_parameters                 # OK
>>> from django.contrib.admin.sites import AdminSite
>>> AdminSite.get_model_admin                                             # OK
>>> "X" in HttpResponse()                                                 # OK, __contains__ = has_header

StorageHandler.backends is declared as cached_property, which is what Django uses and how the other stubs in this repo declare the same pattern.

Each row has a pyright test in tests/pyright/test_missing_symbols.py that fails with that row's stub file reverted.


Part of a set with #406 (signatures), #407 (field descriptors) and #408 (choices=). #406 also edits django-stubs/http/response.pyi, in a different class; every pair merges cleanly in either order.

NorthIsUp and others added 4 commits August 31, 2026 15:13
Each exists at runtime and is importable from its documented public location,
but is missing from the stubs, so a strict checker rejects the import.

- django.test: AsyncClient, AsyncRequestFactory - defined in test/client.pyi,
  never re-exported from the package.
- django.http: HttpResponseBase - defined in http/response.pyi, not re-exported.
- TestCase.captureOnCommitCallbacks - a context manager since Django 3.2.
- django.core.files.storage: storages, StorageHandler, InvalidStorageError -
  the storage-alias registry added in Django 4.2.
- django.utils.http.parse_header_parameters.
Each import fails on main and resolves with the change.
Django 5.0 added it as the supported way to reach a registered ModelAdmin,
so callers stop reaching into the private _registry dict. The stub declared
is_registered but not this.
Django aliases it to has_header, so `"Retry-After" in response` is the
documented spelling. The stub declared only has_header, forcing call sites
to be rewritten around the missing dunder.
ruff sorts the re-export blocks, @contextmanager wants Generator rather than
Iterator, and the missing-symbols tests never used Result.
parse_header_parameters takes max_length (default 10000); backends is a
cached_property, as it is at runtime and as the other stubs declare it.
@NorthIsUp NorthIsUp changed the title Add symbols Django exports but the stubs omit add symbols Django exports but the stubs omit Sep 16, 2026
@sbdchd

sbdchd commented Sep 17, 2026

Copy link
Copy Markdown
Owner

Thanks!

@sbdchd
sbdchd marked this pull request as ready for review September 17, 2026 01:36
@kodiakhq
kodiakhq Bot merged commit 704955b into sbdchd:main Sep 17, 2026
2 checks passed
kodiakhq Bot pushed a commit that referenced this pull request Sep 17, 2026
Ten stub signatures that don't match what Django does. Each one was checked against the Django 6.0.8 runtime rather than inferred from the checker error.

| Stub said | Django actually |
| --- | --- |
| `sql_flush(style: None, tables: None, sequences: None)` | `(style, tables, *, reset_sequences, allow_cascade) -> list[str]` |
| `MigrationLoader.__init__` without `replace_migrations` | has it (defaults `True`) |
| `get_query_string(new_params: dict[str, None])` | holds the values to encode |
| `refresh_from_db(fields: list[str])` | any iterable |
| `URLResolver.url_patterns: list[tuple[str, Callable]]` | `list[URLPattern \| URLResolver]`; `include()` nests resolvers |
| `Client.generic` and `AsyncClient.generic` inherited from the request factories | both run the request through the handler and return a response, like every other verb on them |
| `Client` / `AsyncClient` verbs: `query_params: str \| None` | a mapping; Django passes it to `urlencode` |
| `StreamingHttpResponse(Iterable[bytes])` | `__init__` accepts `str` chunks and encodes them; reads still yield `bytes` |
| `Session.get_decoded/encode/save -> dict[str, int]` | heterogeneous by construction |
| `NonInteractiveMigrationQuestioner` declared `...` | takes `verbosity` and `log` |

Two rows from an earlier revision were withdrawn. `View.dispatch -> HttpResponseBase` is what Django returns, but it breaks the common `def dispatch(...) -> HttpResponse: return super().dispatch(...)` override, so it isn't worth it. `MultiValueDict.__getitem__` is the same change as #300, and Django does return `[]` for an empty list, so that one is left to #300.

**`generic`.** `Client` overrides `get`/`post`/`head`/`options`/`put`/`patch`/`delete`/`trace` to return `HttpResponse` but not `generic`, so it inherits `RequestFactory.generic() -> WSGIRequest`; `AsyncClient` has the same gap against `AsyncRequestFactory`. Any `client.generic("POST", ...)` in a test then gets `.status_code` and `.content` flagged as unknown attributes, because the checker thinks it is holding a request.

**Session payloads.** `django.contrib.auth` stores the session key as `request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)`, which is a `str`. `dict[str, int]` is wrong for every key, and `get_decoded()` returns whatever `signing.loads` produced.

```python
>>> inspect.signature(BaseDatabaseOperations.sql_flush)
(self, style, tables, *, reset_sequences=False, allow_cascade=False)
>>> inspect.signature(MigrationLoader.__init__)
(self, connection, load=True, ignore_no_migrations=False, replace_migrations=True)
>>> inspect.signature(RequestFactory.generic)
(self, method, path, data='', content_type='application/octet-stream', secure=False, *, headers=None, query_params=None, **extra)
```

Every row has a pyright test in `tests/pyright/test_signatures.py` that fails with that row's stub file reverted.

---

Part of a set with #405 (missing symbols), #407 (field descriptors) and #408 (`choices=`). #405 also edits `django-stubs/http/response.pyi`, in a different class; every pair merges cleanly in either order.
kodiakhq Bot pushed a commit that referenced this pull request Sep 17, 2026
Closes #399. Closes #402.

`Field.choices` is typed `_FieldChoices`: the pair/named-group iterable, a mapping, or a zero-argument callable returning either. The per-field `__new__` overloads never caught up. Every one of them lists only the pair iterable, and 17 add a `type[TextChoices]` or `type[IntegerChoices]`. So at the constructor, which is the only place anyone writes `choices=`, three spellings Django accepts were rejected:

| Spelling | Django | Stub before |
| --- | --- | --- |
| `choices={"a": "A"}` | accepted since 5.0 | rejected on every field (#399) |
| `TextField(choices=SomeTextChoices)` | accepted | rejected; `CharField` took it, `TextField` did not (#402) |
| `choices=some_callable` | accepted; serializes the reference, so adding a member needs no migration | rejected on every field |

All three verified on Django 6.0.8:

```python
>>> models.CharField(max_length=8, choices={"a": "A"}).choices
[('a', 'A')]
>>> models.TextField(choices=Kind).choices
[('a', 'A')]
>>> models.CharField(max_length=8, choices=lambda: [("a", "A")]).choices
<django.utils.choices.CallableChoiceIterator object at ...>
```

One generic alias, `_ChoicesFor[value, choices_class]`, replaces the hand-written unions on all 63 `choices=` parameters: the 49 in `fields/__init__.pyi` plus the 14 in `related`, `files`, `json`, `generated` and the postgres `ArrayField`. The second parameter keeps the precision the overloads already had: string fields take `TextChoices`, integer fields take `IntegerChoices`, the rest take the `Choices` base. An `IntegerField` handed a `TextChoices` class was an error before and still is; there is a test for that so the widening can't quietly become a loosening.

Five pyright tests in `tests/pyright/test_choices.py`. The positive ones fail against the current stub; the precision test passes both before and after.

---

Part of a set with #405 (missing symbols), #406 (signatures) and #407 (field descriptors). #407 also edits `fields/__init__.pyi`, `files.pyi`, `json.pyi` and `related.pyi`; the hunks are different declarations and the two merge cleanly in either order.
kodiakhq Bot pushed a commit that referenced this pull request Oct 9, 2026
Closes #116.

Four field descriptor types that force a `cast()` or a dead guard at the call site.

### `ForeignKey`/`OneToOneField` with a lazy string reference

```python
class M(models.Model):
    fk = models.ForeignKey("labs.LabOrder", on_delete=models.CASCADE, null=True)

reveal_type(m.fk)   # before: None      <-- not "unknown", *absent*
                    # after:  Any | None
```

With `to: type[_M] | str`, a string reference gives `_M` nothing to solve from, and on the `null=True` overload the unsolved var collapses the whole field type to `None`. Every read of the field then errors, and the error reads like a nullable-FK bug in the application. Giving `_M` a PEP 696 default of `Any` makes the field `Any` (required) or `Any | None` (`null=True`): unknown rather than absent, with the same nullable shape a class reference gets.

`Any` is only the default. An explicit parameter still resolves to the model, and composes with `null=True`:

```python
untyped   = models.ForeignKey("app.Thing", on_delete=models.CASCADE)               # -> Any
typed     = models.ForeignKey[Thing]("app.Thing", on_delete=models.CASCADE)        # -> Thing
typed_null = models.ForeignKey[Thing | None]("app.Thing", ..., null=True)          # -> Thing | None
```

The lazy string is usually there to avoid an import cycle, and the model can still be imported under `TYPE_CHECKING` and named in the subscript.

No separate overload is added for the string case: `to: type[_M] | str` with the default on `_M` is enough. A string reference still goes through the same overloads as a class reference, so a misspelt `related_name` is still an error, two stray positionals still fail rather than being bound to `related_name`/`related_query_name`, and a `null=True` `OneToOneField` reads `Any | None`. All three are pinned by tests.

One trade-off to state: with a default on `_M`, strict-mode pyright no longer reports `reportMissingTypeArgument` for a bare `ForeignKey` annotation, since it now has a type argument. That is the intended behaviour of PEP 696, but it does mean a bare annotation silently reads as `Any`.

### `JSONField`

`_A` has no PEP 696 default, so an unparameterized `models.JSONField(...)` leaves the var unsolved; mypy errors on the declaration and strict-mode pyright on every read. This defaults it to `Any`, the same pattern `query.pyi` already uses for `_Row`.

### `FileField`

Assignment accepts a `File` or a path `str`; reads return the descriptor. Assigning a `SimpleUploadedFile`, which is the normal thing to do in a test, was rejected.

### `Field.max_length`

Declared `int` as a class attribute while `__init__` in the same file accepts `int | None`. `CharField(max_length=None)` is legal wherever the backend reports `supports_unlimited_charfield` (Postgres does), and Django's own `cast_db_type` and `description` branch on it being `None`, so a `max_length is None` guard in application code is live, not dead. Code that assigned `f.max_length` straight to an `int` will now need the guard.

Every change has a pyright test in `tests/pyright/test_field_descriptors.py` that fails with its stub file reverted.

---

Part of a set with #405 (missing symbols), #406 (signatures) and #408 (`choices=`). #408 also edits `fields/__init__.pyi`, `files.pyi`, `json.pyi` and `related.pyi`; the hunks are different declarations and the two merge cleanly in either order.
UnknownPlatypus added a commit to UnknownPlatypus/django-stubs that referenced this pull request Nov 11, 2026
# I have made things!

While triaging the merged [django-types](https://github.com/sbdchd/django-types) PRs, many turned out to be already fixed here, but nothing ran the behaviour through pyright, pyrefly and ty, and some of it had no test at all. This adds those tests, with no stub changes:

- `prefetch_related()` overloads and `Prefetch.queryset`
- managers not supporting `len()`, indexing or `delete()` like querysets
- `execute_wrapper()` and `constraint_checks_disabled()` as context managers
- the async queryset methods (`aget`, `afirst`, `acreate`, `aiterator`, `async for`)
- `upload_to` callables taking `(instance, filename)`
- `User.objects` as `UserManager[User]`
- `admin.register()` keeping the admin subclass, and the admin action/display decorators keeping the signature
- `AdminSite.get_model_admin()` and `LogEntry.objects.log_actions()` overloads
- `formset_factory()`, `@receiver`, `@deconstructible`, `keep_lazy_text`, the cache view decorators and `request.headers`

## Related issues
Tests proposed while triaging sbdchd#426, sbdchd#425, sbdchd#420, sbdchd#405, sbdchd#350, sbdchd#330, sbdchd#310, sbdchd#308, sbdchd#288, sbdchd#262, sbdchd#238, sbdchd#120, sbdchd#119, sbdchd#105, sbdchd#42, sbdchd#37, sbdchd#8, sbdchd#2.

## AI Policy
- [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
UnknownPlatypus added a commit to typeddjango/django-stubs that referenced this pull request Nov 11, 2026
# I have made things!

While triaging the merged [django-types](https://github.com/sbdchd/django-types) PRs, many turned out to be already fixed here, but nothing ran the behaviour through pyright, pyrefly and ty, and some of it had no test at all. This adds those tests, with no stub changes:

- `prefetch_related()` overloads and `Prefetch.queryset`
- managers not supporting `len()`, indexing or `delete()` like querysets
- `execute_wrapper()` and `constraint_checks_disabled()` as context managers
- the async queryset methods (`aget`, `afirst`, `acreate`, `aiterator`, `async for`)
- `upload_to` callables taking `(instance, filename)`
- `User.objects` as `UserManager[User]`
- `admin.register()` keeping the admin subclass, and the admin action/display decorators keeping the signature
- `AdminSite.get_model_admin()` and `LogEntry.objects.log_actions()` overloads
- `formset_factory()`, `@receiver`, `@deconstructible`, `keep_lazy_text`, the cache view decorators and `request.headers`

## Related issues
Tests proposed while triaging sbdchd#426, sbdchd#425, sbdchd#420, sbdchd#405, sbdchd#350, sbdchd#330, sbdchd#310, sbdchd#308, sbdchd#288, sbdchd#262, sbdchd#238, sbdchd#120, sbdchd#119, sbdchd#105, sbdchd#42, sbdchd#37, sbdchd#8, sbdchd#2.

## AI Policy
- [ ] I have read and agree to the [AI Policy](https://github.com/typeddjango/django-stubs/blob/master/.github/AI_POLICY.md), removed any "Co-Authored-By" lines attributing coding agents, and manually reviewed the final result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants